package com.mkj.draw;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

@SuppressWarnings("all")
/**
 * @Author Arrebol
 * @Date 2024/8/4 16:03
 * @Project graphical programming
 * @Description：
 * 绘制简单图形
 */
public class SimpleDrawDemo1 {

    private final String RECT_SHAPE = "rect";
    private final String OVAL_SHAPE = "oval";

    private Frame frame = new Frame("这里测试绘图");

    Button drawRectangle=new Button("绘制矩形");
    Button drawOval=new Button("绘制椭圆");
    Button clear=new Button("清空画布");

    //定义一个变量记录当前要记录的是什么图形
    private String shape = "";

    //自定义类，继承Canvas类，重写paint方法完成绘图
    private class MyCanvas extends Canvas{
        @Override
        public void paint(Graphics g) {
            //绘制不同的图形
            if(RECT_SHAPE.equals(shape)){
                //绘制矩形
                //设置当前画笔的颜色为黑色
                g.setColor(Color.BLACK);
                g.drawRect(100,100,150,100);
            }else if(OVAL_SHAPE.equals(shape)){
                //绘制椭圆
                g.setColor(Color.RED);
                g.drawOval(100,100,150,100);
            }
        }
    }

    //创建自定义的画布对象
    MyCanvas canvas=new MyCanvas();

    public static void main(String[] args) {
        new SimpleDrawDemo1().init();
    }

    public void init() {
        //组装视图
        drawRectangle.addActionListener(e->{
            //修改标记的值为RECT
            shape=RECT_SHAPE;
            canvas.repaint();
        });
        drawOval.addActionListener(e->{
            shape=OVAL_SHAPE;
            canvas.repaint();
        });
        //创建Panel容器，其中放置两个按钮
        Panel panel=new Panel();
        panel.add(drawRectangle);
        panel.add(drawOval);
        frame.add(panel,BorderLayout.SOUTH);
        //canvas的大小需要设置
        canvas.setPreferredSize(new Dimension(300,200));
        frame.add(canvas);
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        frame.pack();
        frame.setVisible(true);
    }


}
